from flask import Blueprint, request, jsonify
from app.Service.UserService import UserService
from app.Utils.response import success, error
from app.Utils.exceptions import BusinessException
from app.db import db

user_bp = Blueprint('user', __name__, url_prefix='/user')
service = UserService(db)


@user_bp.route('/add', methods=['POST'])
def add_user():
    """新增用户"""
    data = request.get_json()

    # 校验必填参数
    required_fields = ['username', 'password', 'role', 'status']
    for field in required_fields:
        if field not in data:
            return error(400, f"缺少必要参数: {field}")

    try:
        result = service.add_user(data)
        return success(result, "用户新增成功")
    except BusinessException as e:
        return error(e.code, e.message)
    except Exception as e:
        return error(500, f"服务器内部错误: {str(e)}")

@user_bp.route('/delete/<id>', methods=['DELETE'])
def delete_user(id):
    """删除用户"""
    try:
        service.delete_user(int(id))
        return success(None, "用户删除成功")
    except BusinessException as e:
        return error(e.code, e.message)
    except Exception as e:
        return error(500, f"服务器内部错误: {str(e)}")


@user_bp.route('/batchDelete', methods=['DELETE'])
def delete_users():
    """批量删除用户"""
    data = request.get_json()
    ids = data.get('ids', [])

    if not ids:
        return error(400, "缺少必要参数: ids")

    try:
        service.delete_users(ids)
        return success(None, "用户批量删除成功")
    except BusinessException as e:
        return error(e.code, e.message)
    except Exception as e:
        return error(500, f"服务器内部错误: {str(e)}")


@user_bp.route('/list', methods=['GET'])
def list_users():
    """分页查询用户"""
    page = request.args.get('Page', default=1, type=int)
    page_size = request.args.get('pageSize', default=10, type=int)

    try:
        result = service.list_users(page, page_size)
        return success(result, "用户分页查询成功")
    except BusinessException as e:
        return error(e.code, e.message)
    except Exception as e:
        return error(500, f"服务器内部错误: {str(e)}")


@user_bp.route('/update', methods=['POST'])
def update_user():
    """编辑用户"""
    data = request.get_json()

    try:
        result = service.update_user(data)
        return success(result, "用户编辑成功")
    except BusinessException as e:
        return error(e.code, e.message)
    except Exception as e:
        return error(500, f"服务器内部错误: {str(e)}")


@user_bp.route('/<id>', methods=['GET'])
def get_user(id):
    """根据ID查询用户"""
    try:
        result = service.get_user(int(id))
        return success(result, "用户查询成功")
    except BusinessException as e:
        return error(e.code, e.message)
    except Exception as e:
        return error(500, f"服务器内部错误: {str(e)}")


@user_bp.route('/search', methods=['GET'])
def search_users():
    """根据用户名搜索用户"""
    username = request.args.get('username', '')

    try:
        result = service.search_users(username)
        return success(result, "用户搜索成功")
    except BusinessException as e:
        return error(e.code, e.message)
    except Exception as e:
        return error(500, f"服务器内部错误: {str(e)}")